<?php
//个人中心
Namespace Api\Controller;
use Think\Controller;
use Api\Model;
class PersonApiController extends ApiBaseController {


    //获取默认用户名
    public function getDefaultUserName()
    {
        $strUsername = trim(I("username"));
        return $strUsername;
    }
     //注册用户
    public function registerUser(){
        $stravatar=$_POST["avatar"];
        if(strlen($stravatar)>100)
        {
            ShowJsonReturnAndDie(null,true,"头像网址过长");
        }
        $strName = $_POST["name"];
        $strSex = $_POST["sex"];
        $strBirthday = $_POST["birthday"];
        $strToken = $_POST["token"];
        //$stravatar="china";
        //$strName = "邓邓";
        //$strSex = "男";
        //$strBirthday = "20010101";
        //$strToken="";

        $mdlParent =new \Api\Model\AppParentsModel();
        $iParentID = $this->checkAndGetParentID($strToken);
        //$iParentID =4;
        $stuDb =  $mdlParent->getStudentDb();
        $arr = $stuDb->where("parentid=%d and name='%s'",$iParentID,$strName)->field("id")->find();
        if($arr!=null)
        {
            ShowJsonReturnAndDie(null,true,"此学生已经注册");
        }
        $arrMax =  $stuDb->field(" max(id) as maxid ")->find();
        $stuUsername = $arrMax["maxid"]+100000000;
        $strDbDate = $this->DatetimeToDbFormat($strBirthday);
        $arrStudent=array(
            "avatar"=>$stravatar,
            "username"=>$stuUsername,
            "name"=>$strName,
            "sex"=>$strSex,
            "birthday"=>$strDbDate,
            "is_delete"=>1,
            "sectionid"=>0,
            "status"=>1,
            "password"=>"123456",
            "parentid"=>$iParentID,
            "isreg"=>1,   // 线上注册学员
            "regfrom"=>4  // 标识手机注册，乐学园注册为零
        );

        $arrAddedStudentInfo = $stuDb->add($arrStudent);
        $strDefault =   $mdlParent->getDefaultStudentByParentID($iParentID);
        if($strDefault==null){
           $strErrorNew = $mdlParent->setDefaultStudent($iParentID,$stuUsername);
           if($strErrorNew!="")
           {
               ShowJsonReturnAndDie(null,true,$strErrorNew);
           }
        }
        ShowJsonReturnAndDie(array("username"=>$stuUsername));
    }
    //设置默认学员
    public function setDefaultUser(){
        $strUsername =  I("defaultUser");
        $mdlParent =new \Api\Model\AppParentsModel();
        $iParentID =$this->checkAndGetParentID(I("token"));
        $stuDB = $mdlParent->getStudentDb();
        $arrStudent =   $stuDB->where("username='%s' and parentid=%d",$strUsername,$iParentID)->find();
        if($arrStudent==null)
        {
            ShowJsonReturnAndDie(null,true,"请添加学生");
        }
        $strErrorNew =  $mdlParent->setDefaultStudent($iParentID,$strUsername);
        if($strErrorNew!="")
        {
            ShowJsonReturnAndDie(null,true,$strErrorNew);
        }
        ShowJsonReturnAndDie(null);
    }

    //获取学员个人信息
    public function getUserInfo(){
        $strUsername = $this->getDefaultUserName();
        $strToken=I("token");
        // $strUsername="100464508";
        $mdlHr =new \Api\Model\HrModel();
        $mdlParent =new Model\AppParentsModel();
        $arrStudent = $mdlParent->getStudentByUsername($strUsername);
        $iSectionID = $arrStudent["sectionid"];
        $strSchoolName =$iSectionID>0? $mdlHr->getSchoolName($iSectionID):"";
        $iRecCnt =$arrStudent["apprecordcount"]==null?"0":$arrStudent["apprecordcount"];
        $iCollectCnt = $arrStudent["appcollectioncount"]==null?"0":$arrStudent["appcollectioncount"];
        $iStatus = $arrStudent["IsReg"]==1?1:0; // 1线上学员(包含乐学园注册的) 0 线下学员
        $arrReturnInfo = array("username"=>$arrStudent["username"],
            "name"=>$arrStudent["name"],
            "avatar"=>$arrStudent["avatar"],
            "sex"=>$arrStudent["sex"],
            "age"=>$arrStudent["age"],
            "birthday"=>DbDateFormat($arrStudent["birthday"]),
            "school"=>$strSchoolName,
            "status"=>$iStatus,
            "nectar"=>qwFormatData($arrStudent["nectar"]),
            "gold"=>qwFormatData($arrStudent["gold"]),
            "recorderCount"=>$iRecCnt,
            "collectionCount"=>$iCollectCnt
            //"level" =>0,        //等级 待完成
            //"nectar" => "102",  //花蜜
            //"gold" => "109" ,    //金币

        );
        ShowJsonReturnAndDie($arrReturnInfo);
    }

    //修改个人信息
    public function updateUserInfo(){
        $strBirthday = qwTrimStr(I("birthday"));
        $strUsername = $this->getDefaultUserName();
        $strName = qwTrimStr(I("name"));
        $strAvatar=qwTrimStr(I("avatar"));
        if(strlen($strAvatar)>100)
        {
            ShowJsonReturnAndDie(null,true,"头像网址过长");
        }
        $strSex = qwTrimStr(I("sex"));
        $arrEditInfo = array();
        $bIsEdit = false;
        if($strBirthday!="")
        {
            $strDate =   $this->DatetimeToDbFormat($strBirthday);
            $arrEditInfo["birthday"]=$strdate;
            $bIsEdit = true;
        };
        if($strName!="")
        {
            $arrEditInfo["name"]=$strName;
            $bIsEdit = true;
        }
        if($strAvatar!="")
        {
            $arrEditInfo["avatar"]=$strAvatar;
            $bIsEdit = true;
        }
        if($strSex!="")
        {
            $arrEditInfo["sex"]=$strSex;
            $bIsEdit = true;
        }
        if(!$bIsEdit)
        {
            ShowJsonReturnAndDie(null,true,"没有要修改的内容");
        }
        $mdlParents =new Model\AppParentsModel();
        $mdlParents->editStudentInfo($strUsername,$arrEditInfo);
        ShowJsonReturnAndDie(null);
    }

    //修改手机号
    public function changePhone(){
        $mdlSms =new \Api\Model\AppSmsModel();
        $strError = $mdlSms->IsCodeValid(I("serialNumber"),I("code"));
        if($strError!="")
        {
            ShowJsonReturnAndDie(null,true,$strError);
        }
        $strToken = I("token");
        $strPhone=I("newPhone");
        $mdlParent = new \Api\Model\AppParentsModel();
        $iParentID = $this->checkAndGetParentID($strToken);
        $tbl = $mdlParent->getDb();
        $arrParent =   $tbl->where("phone='%s'",$strPhone)->find();
        if($arrParent!=null)
        {
            ShowJsonReturnAndDie(null,true,"新手机号使用中");
        }
        $tbl->where("id=%d",$iParentID)->save(array("phone"=>$strPhone));
        ShowJsonReturnAndDie(null);
    }


     //我的花蜜
    public function getNectar(){
        $strUsername = $this->getDefaultUserName();
        $iType = I("type");
        $mdlParent =new \Api\Model\AppParentsModel();
        $dbHistory =  $mdlParent->getNectarHistoryDb();
        $arrResult =   $dbHistory->where("username='%s'",$strUsername)->order("id desc")->select();
        $arrReturn =array();
        foreach($arrResult as $row)
        {
            $strTime =  DbDateFormat($row["addtime"]);
            $arrReturn[] = array(
                "detail"=>$row["detail"],
                "duration"=>$row["duration"],
                "time"=> $strTime,
                "count"=> $row["count"],
                "type"=>$row["type"]
            );
        }
        ShowJsonReturnAndDie($arrReturn);
    }


      //花蜜兑换记录
    public function nectarExchangeRecording(){
        $strUsername = $this->getDefaultUserName();
        //$strUsername = "100001023";
        $mdlParent =new \Api\Model\AppParentsModel();
        $arrStudent =   $mdlParent->getStudentByUsername($strUsername);
        $dbGoldHistory =    $mdlParent->getGoldHistoryDb();
        $arrResult0 =  $dbGoldHistory->where("username='%s'",$strUsername)->order("id desc")->select();
        $arrExchange = array();
        foreach($arrResult0 as $row)
        {
            $arrExchange[]=array(
                "detail"=>$row["detail"],
                "time"=>DbTimeFormat($row["addtime"]),
                "count"=>qwFormatData($row["count"]),
                "action"=>$row["action"]
            );
        }
        ShowJsonReturnAndDie(array(
            "nectarTotal"=>qwFormatData($arrStudent["nectar"]),
            "gold"=>qwFormatData($arrStudent["gold"]),
            "goldExchanges"=>$arrExchange
        ));
    }

    //增加花蜜
    public function addNectar(){
        $strUsername=$this->getDefaultUserName();
        $iCnt=I("count");
        //$strUsername="100001053";
        //$iCnt=10;
        $mdlParent =new \Api\Model\AppParentsModel();
        $strError =  $mdlParent->addNectar($strUsername,$iCnt,"增减花蜜");
        if($strError!="")
        {
            ShowJsonReturnAndDie(null,true,$strError);
        }else{
            ShowJsonReturnAndDie(null);
        }
    }
    //兑换金币
    public function exchangeGold(){
        $iExchangeNectarNum =  I("nectarCount");
        $strUsername =  $this->getDefaultUserName();
        //  $iExchangeNectarNum =  50;
        //   $strUsername =  "100001030";
        $mdlParent =new \Api\Model\AppParentsModel();
        $arrUsername =   $mdlParent->getStudentByUsername($strUsername);
        $iCurrentNectar = $arrUsername["nectar"];
        $iGold = $arrUsername["gold"];
        if(!is_numeric($iExchangeNectarNum))
        {
            ShowJsonReturnAndDie(null,true,"兑换数量为数字");
        }
        if($iExchangeNectarNum<=0)
        {
            ShowJsonReturnAndDie(null,true,"兑换数量必须大于零");
        }
        if($iExchangeNectarNum>$iCurrentNectar)
        {
            ShowJsonReturnAndDie(null,true,"当前花蜜不足，无法兑换");
        }
        $strDetail ="花蜜兑换";
        $cfgDb = $mdlParent->getConfigDb();
        $arrRate = $cfgDb->field("nectarexchangerate")->find();  // 花蜜兑换金币的比例
        $dRate = $arrRate["nectarexchangerate"];
        $iExchangeGold =$iCurrentNectar*$dRate;
        $iFinalGold = $iGold+$iExchangeGold;
        $iFinalNectar = $iCurrentNectar-$iExchangeNectarNum;
        $NectarHistoryDb = $mdlParent->getNectarHistoryDb();
        $NectarHistoryDb->add(array(
            "detail"=>$strDetail,
            "duration"=>0,
            "addtime"=>date("Y-m-d H:i:s"),
            "count"=>$iExchangeNectarNum,
            "username"=>$strUsername,
            "type"=>1,
            "relateid"=>0,
            "relateitem"=>"exchangegold",
            "currentnectar"=>$iCurrentNectar,
            "finalnectar"=>$iFinalNectar,
            "exchangegold"=>$iExchangeGold,
            "currentgold"=>$iGold,
            "finalgold"=>$iFinalGold
        ));
        $goldHistoryDb =  $mdlParent->getGoldHistoryDb();
        $goldHistoryDb->add(array(
            "detail"=>$strDetail,
            "addtime"=>date("Y-m-d H:i:s"),
            "count"=>$iExchangeGold,
            "action"=>1,
            "username"=>$strUsername,
            "currentnectar"=>$iCurrentNectar,
            "finalnectar"=>$iFinalNectar,
            "exchangenectar"=>$iExchangeNectarNum,
            "currentgold"=>$iGold,
            "finalgold"=>$iFinalGold
        ));
        $mdlParent->getStudentDb()->where("username='%s'",$strUsername)->save(array(
            "nectar"=>$iFinalNectar,
            "gold"=>$iFinalGold
        ));
        ShowJsonReturnAndDie(null);
    }

    //我的金币
    public function goldRecording(){
        //$iType = I("type"); // 0：收入 1：支出
        $strUsername=$this->getDefaultUserName();
        // $iAction = $iType==0 ? 1:0;// action 0:花费 1：收入
        $mdlParent =new \Api\Model\AppParentsModel();
        $arrUsername =   $mdlParent->getStudentByUsername($strUsername);
        $iGold = $arrUsername["gold"];
        $arrHistory0 = $mdlParent->getGoldHistoryDb()->where("username='%s'",$strUsername)->field("action,id,detail,duration,addtime,count")->order("id desc")->select();
        $arrHistory = array();
        foreach($arrHistory0 as $row)
        {
            $iType = $row["action"]==0?1:0; // action 0:花费 1：收入
            $arrHistory[]=array(
                "detail"=>$row["detail"],
                "duration"=>$row["duration"],
                "time"=>DbTimeFormat($row["addtime"]),
                "count"=>$row["count"],
                "duration"=>$row["duration"],
                "type"=>$iType
            );
        }
        ShowJsonReturnAndDie(array(
            "goldTotal"=>qwFormatData($iGold),
            result=>$arrHistory
        ));
    }
    //我的录音
    public function myRecordings(){
        $strUsername = $this->getDefaultUserName();
        //$strUsername = "100001030";
        $mdlRecord =new \Api\Model\AppRecordModel();
        $arrRecordList =     $mdlRecord->getRecordList($strUsername);
        $strBaseUrl = $mdlRecord->getBaseUrl();
        $arrReturn=array();
        foreach($arrRecordList as $row){
            $iTempID = intval($row["id"]."");
            $arrReturn[]=array(
                "recordingId"=>$iTempID,
                "url"=>$strBaseUrl.$row["path"],
                "time"=>DbDateFormat($row["addtime"]),
                "duration"=>$row["duration"],
                "title"=>$row["title"]
            );
        }
        ShowJsonReturnAndDie($arrReturn);
    }

    //删除我的录音
    public function deleteRecording(){
        $strUsername = $this->getDefaultUserName();
        $iID = I("recordingId");
        //$strUsername="100001030";
        //$iID=2;
        $mdlRecord =new \Api\Model\AppRecordModel();
        $mdlRecord->delRecord($strUsername,$iID);
        ShowJsonReturnAndDie(null);
    }

    //我的通知和群消息
    public function getMyMessages(){
        $strUsername = $this->getDefaultUserName();
        // $strUsername="100001030";
        $mdlParent = new \Api\Model\AppParentsModel();
        $arrMsgList0 = $mdlParent->getMessageList($strUsername);
        $arrnotis = array();
        $arrmessages = array();
        // 1:notis 2:message
        foreach($arrMsgList0 as $row)
        {
            switch($row["msgtype"])
            {
                case 1:
                    $arrnotis[]=array(
                        "tag"=>$row["tag"],
                        "title"=>$row["msgtitle"],
                        "time"=>DbTimeFormat($row["addtime"]),
                        "notiId"=>$row["id"]
                    );
                    break;
                case 2:
                    $arrmessages[]=array(
                        "tag"=>$row["tag"],
                        "title"=>$row["msgtitle"],
                        "time"=>DbTimeFormat($row["addtime"]),
                        "messageId"=>$row["id"]
                    );
                    break;
            }
        }
        ShowJsonReturnAndDie(array(
            "notis"=>$arrnotis,
            "messages"=>$arrmessages
        ));
    }

    //我的收藏 (由于磨耳朵数据库没定，此结果可能算错误)
    public function myCollections(){
        $strUsername= $this->getDefaultUserName();
        $iType = I("type");
        // 1:磨耳朵 2：阅读 3：口语
        //$strUsername = "100001030";
        //$iType=2;
        $mdlParent =new \Api\Model\AppParentsModel();
        $arrResult = $mdlParent->getCollections($strUsername,$iType);
        ShowJsonReturnAndDie($arrResult);

    }

    //收藏
    public function collectCourse(){
        $strUsername= $this->getDefaultUserName();
        $iType = I("type");
        $iCourseId = I("courseId");
        if($iCourseId<=0)
        {
            ShowJsonReturnAndDie(null,true,"当前收藏不存在");
        }
        //$strUsername = "100001030";
        //$iType=2;
        //$iCourseId=399;
        $mdlParent =new \Api\Model\AppParentsModel();
        $strError =  $mdlParent->collectCourse($strUsername,$iType,$iCourseId);
        if($strError!="")
        {
            ShowJsonReturnAndDie(null,true,$strError);
        }
        ShowJsonReturnAndDie(null);
    }

    //取消收藏
    public function cancelCollection(){
        $strUsername= $this->getDefaultUserName();
        $iType = I("type");
        $iCourseId = I("courseId");
        if($iCourseId<=0)
        {
            ShowJsonReturnAndDie(null,true,"当前收藏不存在");
        }
        //$strUsername = "100001030";
        //$iType=2;
        //$iCourseId=399;
        $mdlParent =new \Api\Model\AppParentsModel();
        $mdlParent->cancelCollection($strUsername,$iType,$iCourseId);
        ShowJsonReturnAndDie();
    }

    //意见反馈
    public function feedback(){
        $strToken = I("token");
        $strContent = trim(I("content"));
        $strContact = ""; //前端无联系方式
        if($strContent==""){
            ShowJsonReturnAndDie(null,false,"请填写反馈内容");
        }
        //if($strContact==""){
        //    ShowJsonReturnAndDie(null,false,"请填写联系方式");
        //}
        $mdlParent =new \Api\Model\AppParentsModel();
        $iParentID = $mdlParent->getIdByToken($strToken); 
        $mdlParent->getFeedbackDb()->add(array(
            "content"=>$strContent,
            "contact"=>$strContact,
            "addtime"=>date("Y-m-d H:i:s",time()),
            "parentid"=>$iParentID,
            "status"=>0,
            "memo"=>""
        ));
        ShowJsonReturnAndDie(null);
    }

    //上传头像
    public function uploadAvatar(){
        $strBaseUrl = C("PUBLIC_UPLOAD_URL")."avatar/";

        //引入UploadFile类
        import('ORG.Net.UploadFile');
        //实例化UploadFile类
        $upload  = new \UploadFile();
        //设置文件大小
        $upload -> maxSize = 3292200;
        //设置文件保存规则唯一
        $upload->saveRule = 'uniqid';

        $upload->subType = 'date';
        //设置上传文件的格式
        $upload -> allowExts = array('jpg','png','jpeg');
        $upload->autoSub=true;
        //保存路径
        $upload->savePath ='./Public/Uploads/avatar/';
        //设置需要生成缩略图，仅对图像文件有效
        $upload->thumb = false;
        //设置需要生成缩略图的文件前缀
        $upload->thumbPrefix = 'm_';  //生产缩略图也可以根据需要生成1张或多张，2张：'m_,s_'
        //设置缩略图最大宽度
        $upload->thumbMaxWidth = '150';//2张的不同设置：'150,200'
        //设置缩略图最大高度
        $upload->thumbMaxHeight = '200';
        //删除原图
        $upload->thumbRemoveOrigin = true;
        //上传失败返回错误信息
        if(!$upload->upload()){
            ShowJsonReturnAndDie(null,true,$upload->getErrorMsg());
            //ShowJsonReturnAndDie(null,true,"上传失败请稍后再试!");
            //$this->error($upload->getErrorMsg());
        }   //获取上传文件的信息
        $arrInfoes= $upload->getUploadFileInfo();
        $info=$arrInfoes[0];
        $strFilePath =$info["savename"];
        // $strFileDir = $info["savepath"];
        $strUrl = $strBaseUrl.$strFilePath;
        ShowJsonReturnAndDie(array("avatarUrl"=>$strUrl));
    }

    //删除学员
    public function deleteUsername(){
        $strToken=I("token");
        $mdlParent =new \Api\Model\AppParentsModel();
        $iParent = $mdlParent->getIdByToken($strToken);
        $strDeleteUsername =I("deleteUsername");
        $db = $mdlParent->getStudentDb();
        $db->where("username='%s' and parentid=%d",$strDeleteUsername,$iParent)->save(array("parentid"=>"0"));
        //die($db->getLastSql());
        // 获取默认用户并更新当前默认用户
        $strNewDefaultUsername = $mdlParent->getDefaultStudentByParentID($iParent);
        $mdlParent->where("id=%d",$iParent)->save(array("defaultchildusername"=>$strNewDefaultUsername));
            //die($mdlParent->getLastSql());
        ShowJsonReturnAndDie(null);
    }
    //帮助文档
    public function getDocumentations(){
        $strUsername = $this->getDefaultUserName();
        $mdlParent =new \Api\Model\AppParentsModel();
        $arrDocs =  $mdlParent->getDocs($strUsername);
        $arrResult = array();
        foreach($arrDocs as $row){
            $arrResult[]=array(
                "title"=>$row["title"],
                "detail"=>$row["detail"]
            );
        }
        ShowJsonReturnAndDie($arrResult);
    }
    //获取绑定的学员列表
    public function getUserList(){
        $strToken = $_POST["token"];
        $mdlParent =new \Api\Model\AppParentsModel();
        $iParentID = $this->checkAndGetParentID($strToken);
        //$iParentID =4;
        $arrStudentList =  $mdlParent->getStudentListByParentID($iParentID);
        $arrResult = array();
        foreach($arrStudentList as $row){
            $arrResult[] = array(
                "avatar" =>$row["avatar"],
                "username" =>$row["username"],
                "name" =>$row["name"],
                "isDefault" =>$row["isdefault"],
                "iParentID"=>$iParentID
            );
        }

        ShowJsonReturnAndDie($arrResult);
    }
    /**
     * 取消自选教材
     */
    public function cancelMaterial(){
        $strUsername = $this->getDefaultUserName();
        $iBookID = I("bookId");
        $mdlLesson =new Model\AppLessonModel();
        $strError =  $mdlLesson->cancelMaterial($strUsername,$iBookID);
        if($strError!=null)
        {
            ShowJsonReturnAndDie(null,true,$strError);
        }
        ShowJsonReturnAndDie(null);
    }
    

}